package edu.nf.controller.room;

import edu.nf.controller.BaseController;
import edu.nf.hotel.util.FileUploadUtil;
import edu.nf.hotel.vo.ResultVO;
import org.nf.web.annotation.RequestMapping;
import org.nf.web.annotation.RequestParam;
import org.nf.web.servlet.view.JsonView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.nf.web.servlet.View;
import java.io.File;
import java.io.IOException;


/**
 * @Data 2023-06-25
 * @Author Lsw
 */
public class UploadPRoomTypeImageController extends BaseController {
    /**
     * 商品默认图片
     */
    private static final String DEFAULT_IMAGE = "default.jpg";

    @RequestMapping("/UploadPRoomType")
    public View upload(@RequestParam("lastImage") String lastImage, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.当前上传的图片
        Part part = req.getPart("attach");

//        // 2.之前的图片
        //String lastImage = req.getParameter("lastImage");

        // 获取图片上传的物理路径
        String path = req.getServletContext().getRealPath("/images/room");

        // 3.删除图片
        if (lastImage != null && !"".equals(lastImage)) {
            File f = new File(path + File.separator + lastImage);
            if (f.exists() && !DEFAULT_IMAGE.equals(lastImage)) {
                f.delete();
            }
        }

        // 4.使用上传工具类来实现文件的上传
        FileUploadUtil fuu = new FileUploadUtil();
        // 设置允许上传文件的大小和类型 - 1MB
        fuu.setMaxSize(1 * 1024 * 1024);
        fuu.setAllowFileExt("jpg,png,jpeg");
        String filename = fuu.upload(part, path);

        ResultVO vo = success(filename);
        vo.setCode(200);
        vo.setMessage("上传成功");
        return new JsonView(vo);
    }
}
